package com.yeshine.opendata.api;

import com.yeshine.opendata.api.model.DataModel;
import com.yeshine.opendata.api.model.DataSetModel;
import com.yeshine.opendata.api.model.Session;
import com.yeshine.opendata.api.model.UserModel;
import com.yeshine.opendata.core.AppException;
import com.yeshine.opendata.entity.*;
import com.yeshine.opendata.entity.SysDictionary;
import com.yeshine.opendata.service.*;
import com.yeshine.opendata.utils.CommonUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Created by taohj on 2014/9/23.
 */


@Component
public class API {




    private static final Map<String, Session> sessionContainer = new HashMap<String, Session>();

    HttpServletRequest request = null;


    @Autowired
    private IUserService userService;

    @Autowired
    private IOrgService orgService;

    @Autowired
    private IMemberService memberService;

    @Autowired
    private IDataSetService dataSetService;

    @Autowired
    private IDataService dataService;


    /**
     * 1.用户登录
     *
     * @param username
     * @param password
     */
    public Result login() throws AppException {


        String username = request.getParameter("username");
        String password = request.getParameter("password");

        if (!StringUtils.hasLength(username)) {
            throw new AppException("用户名不能为空");
        }
        if (!StringUtils.hasLength(password)) {
            throw new AppException("密码不能为空");
        }

        Result result = new Result();
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);

        user = userService.login(user).getTarget();

        if (user == null) {
            result.setMessage("用户名或密码不正确");
            result.setStatus(1);
            return result;
        }


        UserModel userModel = new UserModel();
        userModel.setSessionid(buildSessionId());

        Session session = new Session();
        session.setId(userModel.getSessionid());
        session.setLastTime(new Date());
        session.setUser(userModel);
        sessionContainer.put(session.getId(), session);
        BeanUtils.copyProperties(user, userModel);
        result.setResult(userModel);
        result.setMessage("登录成功");
        result.setStatus(0);
        return result;
    }


    /**
     * 2.用户登出
     *
     * @param sessionid
     */
    public Result loginOff() {
        verifyPermissions();
        String sessionid = request.getParameter("sessionid");
        sessionContainer.remove(sessionid);
        Result result = new Result();
        result.setStatus(0);
        result.setMessage("登出成功");
        return result;
    }


    /**
     * 3.获取某个用户的详细信息
     *
     * @param sessionid
     * @param userid
     */
    public Result getUserInfo() {
        verifyPermissions();
        String userid = request.getParameter("userid");
        if (!StringUtils.hasLength(userid)) {
            throw new AppException("用户编号不能为空");
        }


        User user = userService.getById(Integer.valueOf(userid)).getTarget();

        if (user == null) {
            throw new AppException("该用户不存在");
        }

        UserModel userModel = new UserModel();
        BeanUtils.copyProperties(user, userModel);
        return new Result(userModel);
    }


    /**
     * 4.模糊搜索用户信息
     *
     * @param sessionid
     * @param keyword
     */
    public Result getFuzzyUserInfo() {
        verifyPermissions();
        String keyword = request.getParameter("keyword");

        if (!StringUtils.hasLength(keyword)) {
            throw new AppException("keyword不能为空");
        }

        User user = new User();
        user.setUsername(keyword);
        List<User> users = userService.getList(user).getList();
        List<UserModel> userModels = new ArrayList<UserModel>();
        for (User u : users) {
            UserModel um = new UserModel();
            BeanUtils.copyProperties(u, um);
            userModels.add(um);
        }
        return new Result(userModels);
    }


    /**
     * 5.组织模糊查询-- getFuzzyOrgInfo
     *
     * @param keyword
     */
    public Result getFuzzyOrgInfo() {
        String keyword = request.getParameter("keyword");
        if (!StringUtils.hasLength(keyword)) {
            throw new AppException("关键字(keyword)不能为空");
        }
        Org org = new Org();
        org.setKeyWord(keyword);
        List<Org> orgs = orgService.getList(org).getList();
        Result result = new Result(orgs);
        return result;
    }

    /**
     * 6.组织详细信息查询-- getOrgInfo
     *
     * @param orgid
     */
    public Result getOrgInfo() {
        verifyPermissions();
        String orgid = request.getParameter("orgid");
        if (!StringUtils.hasLength(orgid)) {
            throw new AppException("组织ID不能为空");
        }
        Org org = orgService.getById(Integer.valueOf(orgid)).getTarget();
        if (org == null) {
            return new Result(1, "该组织不存在");
        }
        return new Result(org);
    }

    /**
     * 7.组织内成员信息查询-- getMemberInfoByOrg
     *
     * @param orgid
     * @param memberid
     * @param membername
     */
    public Result getMemberInfoByOrg() {

        String orgid = request.getParameter("orgid");
        String memberid = request.getParameter("memberid");
        String membername = request.getParameter("membername");

        if (!StringUtils.hasLength(orgid)) {
            throw new AppException("组织ID不能为空");
        }

        Org org = new Org(Integer.valueOf(orgid));
        User user = new User();
        user.setUsername(membername);
        Member member = new Member();
        member.setOrg(org);
        member.setId(Integer.valueOf(memberid));
        member.setUser(user);

        List<Member> list = memberService.getList(member).getList();
        return new Result(list);
    }


    /**
     * 8.用户数据集查询
     *
     * @param sessionid
     * @param userid
     */
    public Result getDataSetByUser() {

        verifyPermissions();

        String userid = request.getParameter("userid");


        if (!StringUtils.hasLength(userid)) {
            throw new AppException("用户ID不能为空");
        }


        DataSet dataSet = new DataSet();
        dataSet.setCreater(new User(Integer.valueOf(userid)));

        List<DataSet> dataSets = dataSetService.getList(dataSet).getList();
        List<DataSetModel> dataSetModels = new ArrayList<DataSetModel>();
        for (DataSet ds : dataSets) {
            DataSetModel dm = new DataSetModel();
            BeanUtils.copyProperties(ds, dm);
            dataSetModels.add(dm);
        }
        return new Result(dataSetModels);
    }

    /**
     * 9.组织内数据集查询
     *
     * @param sessionid
     * @param orgid
     */
    public Result getDataSetByOrg() {

        verifyPermissions();
        String orgid = request.getParameter("orgid");


        if (!StringUtils.hasLength(orgid)) {
            throw new AppException("机构ID不能为空");
        }


        DataSet dataSet = new DataSet();
        dataSet.setOrg(new Org(Integer.valueOf(orgid)));
        List<DataSet> dataSets = dataSetService.getList(dataSet).getList();
        List<DataSetModel> dataSetModels = new ArrayList<DataSetModel>();
        for (DataSet ds : dataSets) {
            DataSetModel dm = new DataSetModel();
            BeanUtils.copyProperties(ds, dm);
            dataSetModels.add(dm);
        }
        return new Result(dataSetModels);
    }


    /**
     * 10.数据集内数据信息查询
     */
    public Result getDataByDataSet() {

        verifyPermissions();

        String datasetid = request.getParameter("datasetid");


        if (!StringUtils.hasLength(datasetid)) {
            throw new AppException("数据集ID不能为空");
        }


        Data data = new Data();
        data.setDataset(new DataSet(Integer.valueOf(datasetid)));
        List<Data> datas = dataService.getList(data).getList();
        List<DataModel> dataModels = new ArrayList<DataModel>();
        for (Data d : datas) {
            DataModel dm = new DataModel();
            BeanUtils.copyProperties(d, dm);
            dataModels.add(dm);
        }
        return new Result(dataModels);
    }


    /**
     * 11. 数据集模糊查询
     *
     * @param sessionid
     * @param key
     */
    public Result getFuzzyDataSet() {

        verifyPermissions();


        String key = request.getParameter("key");


        if (!StringUtils.hasLength(key)) {
            throw new AppException("关键词 key 不能为空");
        }
        DataSet dataSet = new DataSet();
        dataSet.setKeyWord(key);
        List<DataSet> dataSets = dataSetService.getList(dataSet).getList();
        return new Result(dataSets);
    }


    /**
     * 14.注册用户
     *
     * @param username
     * @param password
     * @param email
     */

    public Result register() {

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");

        if (!StringUtils.hasLength(username)) {
            throw new AppException("用户名不能为空");
        }

        if (!StringUtils.hasLength(password)) {
            throw new AppException("密码不能为空");
        }

        if (!StringUtils.hasLength(email)) {
            throw new AppException("邮箱不能为空");
        }

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setEmail(email);

        com.yeshine.opendata.utils.Result<User> result = userService.create(user);
        if (result.isSuccess()) {
            return new Result("注册成功");
        } else {
            return new Result(1, result.getMessage());
        }
    }


    /**
     * 15.用户信息修改
     *
     * @param id
     * @param telephone
     * @param realname
     * @param sex
     * @param birthday
     * @param QQ
     * @param headImage
     */

    public Result modifyUserInfo() {

        verifyPermissions();
        String id = request.getParameter("id");
        String telephone = request.getParameter("telephone");
        String realname = request.getParameter("realname");
        String sex = request.getParameter("sex");
        String birthday = request.getParameter("birthday");
        String QQ = request.getParameter("QQ");

        if (!StringUtils.hasLength(id)) {
            throw new AppException("用户ID不能为空");
        }
        if (!StringUtils.hasLength(telephone)) {
            throw new AppException("电话号码不能为空");
        }
        if (!StringUtils.hasLength(realname)) {
            throw new AppException("姓名不能为空");
        }

        if (!StringUtils.hasLength(sex)) {
            throw new AppException("性别不能为空");
        }

        User user = userService.getById(Integer.valueOf(id)).getTarget();
        if (user == null) {
            throw new AppException("用户不存在");
        }
        user.setTelephone(telephone);
        user.setRealname(realname);
        user.setSex(new SysDictionary(Integer.valueOf(sex)));
        user.setBirthday(StringUtils.hasLength(birthday) ? CommonUtil.dateParse(birthday, "yyyy-MM-dd") : null);
        user.setQQ(QQ);

        com.yeshine.opendata.utils.Result<User> result = userService.modify(user, request);
        if (result.isSuccess()) {
            return new Result("修改成功");
        } else {
            return new Result(1, result.getMessage());
        }
    }


    /**
     * 16.组织注册
     *
     * @param name
     * @param superOrgId
     * @param image
     * @param category
     * @param contacts
     * @param telephone
     * @param email
     * @param address
     * @param postcode
     * @param description
     */

    public Result orgRegistration() {
        verifyPermissions();
        String name = request.getParameter("name");
        String superOrgId = request.getParameter("superOrgId");
        String category = request.getParameter("category");
        String contacts = request.getParameter("contacts");
        String telephone = request.getParameter("telephone");
        String email = request.getParameter("email");
        String address = request.getParameter("address");
        String postcode = request.getParameter("postcode");
        String description = request.getParameter("description");


        if (!StringUtils.hasLength(name)) {
            throw new AppException("机构名称(name)不能为空");
        }
        if (!StringUtils.hasLength(category)) {
            throw new AppException("机构分类(category)不能为空");
        }

        Org org = new Org();
        org.setName(name);
        org.setSuperOrg(new Org(Integer.valueOf(superOrgId)));
        org.setContacts(contacts);
        org.setTelephone(telephone);
        org.setEmail(email);
        org.setAddress(address);
        org.setPostcode(postcode);
        org.setDescription(description);

        com.yeshine.opendata.utils.Result<Org> result = orgService.create(org, request);

        if (!result.isSuccess()) {
            throw new AppException(result.getMessage());
        }

        Result rt = new Result(result.getMessage(), org);
        return rt;
    }


    /**
     * 17.组织信息修改—orgInfoModify
     *
     * @param id
     * @param name
     * @param superOrgId
     * @param image
     * @param category
     * @param contacts
     * @param telephone
     * @param email
     * @param address
     * @param postcode
     * @param description
     */
    public Result orgInfoModify() {
        verifyPermissions();
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String superOrgId = request.getParameter("superOrgId");
        String category = request.getParameter("category");
        String contacts = request.getParameter("contacts");
        String telephone = request.getParameter("telephone");
        String email = request.getParameter("email");
        String address = request.getParameter("address");
        String postcode = request.getParameter("postcode");
        String description = request.getParameter("description");


        if (!StringUtils.hasLength(name)) {
            throw new AppException("机构名称(name)不能为空");
        }
        if (!StringUtils.hasLength(category)) {
            throw new AppException("机构分类(category)不能为空");
        }

        Org org = new Org(Integer.valueOf(id));
        org.setName(name);
        org.setSuperOrg(new Org(Integer.valueOf(superOrgId)));
        org.setContacts(contacts);
        org.setTelephone(telephone);
        org.setEmail(email);
        org.setAddress(address);
        org.setPostcode(postcode);
        org.setDescription(description);

        com.yeshine.opendata.utils.Result<Org> result = orgService.modify(org, request);

        if (!result.isSuccess()) {
            throw new AppException(result.getMessage());
        }

        Result rt = new Result(result.getMessage(), org);
        return rt;

    }


    /**
     * 18. 增加组织成员-- inOrgMember
     *
     * @param sessionid
     * @param orgId
     * @param usersid
     * @param roleid
     */
    public Result inOrgMember() {
        verifyPermissions();
        String orgId = request.getParameter("orgId");
        String[] users = request.getParameterValues("usersid");
        String memberroleid = request.getParameter("role");

        List<Member> members = new ArrayList<Member>();
        for (String u : users) {
            Member member = new Member();
            member.setOrg(new Org(Integer.valueOf(orgId)));
            member.setRole(new Role(Integer.valueOf(memberroleid)));
            member.setUser(new User(Integer.valueOf(u)));
        }

        com.yeshine.opendata.utils.Result<Member> result = memberService.create(members);

        if (!result.isSuccess()) {
            return new Result(result.getMessage(), 1, null);
        }
        return new Result(result.getMessage());
    }


    /**
     * 19.删除组织成员-- delOrgMember
     *
     * @param memberid
     */
    public Result delOrgMember() {

        verifyPermissions();

        String members[] = request.getParameterValues("memberid");
        List<Member> memberList = new ArrayList<Member>();

        for (String m : members) {
            Member member = new Member(Integer.valueOf(m));
            memberList.add(member);
        }


        com.yeshine.opendata.utils.Result<Member> result = memberService.remove(memberList);

        if (!result.isSuccess()) {
            return new Result(1, result.getMessage());
        }

        return new Result(result.getMessage());

    }


    /**
     * 20. 组织成员角色修改-- memberRoleModify
     *
     * @param memberid
     * @param roleid
     */
    public Result memberRoleModify() {

        String memberid[] = request.getParameterValues("memberid");
        String roleid = request.getParameter("roleid");

        List<Member> memberList = new ArrayList<Member>();
        for (String m : memberid) {
            Member member = new Member(Integer.valueOf(m));
            member.setRole(new Role(Integer.valueOf(roleid)));
            memberList.add(member);
        }

        com.yeshine.opendata.utils.Result<Member> result = memberService.modify(memberList);
        if (!result.isSuccess()) {
            return new Result(1, result.getMessage());
        }
        return new Result(result.getMessage());
    }


    /**
     * 21.新增数据—addData
     *
     * @param title
     * @param description
     * @param tags
     * @param license
     * @param orgId
     * @param storage
     * @param url
     * @param visibility
     * @param version
     * @param GUID
     * @param dataSetId
     * @param file
     */
    public Result addData() {

        verifyPermissions();
        String sessionid = request.getParameter("sessionid");
        String title = request.getParameter("title");
        String description = request.getParameter("description");
        String tags = request.getParameter("tags");
        String license = request.getParameter("license");
        String orgId = request.getParameter("orgId");
        String storage = request.getParameter("storage");
        String url = request.getParameter("url");
        String visibility = request.getParameter("visibility");
        String version = request.getParameter("version");
        String GUID = request.getParameter("GUID");
        String dataSetId = request.getParameter("dataSetId");

        Session session = sessionContainer.get(sessionid);

        Data data = new Data();
        data.setTitle(title);
        data.setDescription(description);
        data.setTags(tags);
        data.setLicense(license);
        data.setOrg(new Org(Integer.valueOf(orgId)));
        data.setStorage(new SysDictionary(Integer.valueOf(storage)));
        data.setUrl(url);
        data.setVisibility(new SysDictionary(Integer.valueOf(visibility)));
        data.setVersion(version);
        data.setGUID(GUID);
        data.setDataset(new DataSet(Integer.valueOf(dataSetId)));

        com.yeshine.opendata.utils.Result<Data> result = dataService.create(data, request);
        if (!result.isSuccess()) {
            throw new AppException("数据新增失败");
        }
        return new Result(data);
    }


    /**
     * 22.数据修改—updateData
     *
     * @param id
     * @param title
     * @param description
     * @param tags
     * @param license
     * @param orgId
     * @param storage
     * @param url
     * @param visibility
     * @param version
     * @param GUID
     * @param dataSetId
     * @param file
     */

    public Result updateData() {
        verifyPermissions();
        String sessionid = request.getParameter("sessionid");
        String id = request.getParameter("id");
        String title = request.getParameter("title");
        String description = request.getParameter("description");
        String tags = request.getParameter("tags");
        String license = request.getParameter("license");
        String orgId = request.getParameter("orgId");
        String storage = request.getParameter("storage");
        String url = request.getParameter("url");
        String visibility = request.getParameter("visibility");
        String version = request.getParameter("version");
        String GUID = request.getParameter("GUID");
        String dataSetId = request.getParameter("dataSetId");

        if (!StringUtils.hasLength(id)) {
            throw new AppException("数据ID不能是空的");
        }

        Session session = sessionContainer.get(sessionid);

        Data data = dataService.getById(Integer.valueOf(id)).getTarget();
        data.setTitle(title);
        data.setDescription(description);
        data.setTags(tags);
        data.setLicense(license);
        data.setOrg(new Org(Integer.valueOf(orgId)));
        data.setStorage(new SysDictionary(Integer.valueOf(storage)));
        data.setUrl(url);
        data.setVisibility(new SysDictionary(Integer.valueOf(visibility)));
        data.setVersion(version);
        data.setGUID(GUID);
        data.setDataset(new DataSet(Integer.valueOf(dataSetId)));

        com.yeshine.opendata.utils.Result<Data> result = dataService.create(data, request);
        if (!result.isSuccess()) {
            throw new AppException("数据更新失败");
        }
        return new Result(data);
    }


    /**
     * 22. 数据删除—delData
     *
     * @param action
     * @param sessionid
     * @param dataid
     */
    public Result delData() {
        verifyPermissions();
        String dataid = request.getParameter("dataid");
        int id = Integer.valueOf(dataid);

        Data data = new Data(id);
        com.yeshine.opendata.utils.Result result = dataService.remove(data);
        if (!result.isSuccess()) {
            throw new AppException(result.getMessage());
        }
        return new Result(result.getMessage());
    }


    /**
     * 24.数据集新增--addDataSet
     *
     * @param name
     * @param description
     * @param themeId
     * @param orgId
     */
    public Result addDataSet() {
        verifyPermissions();
        String sessionid = request.getParameter("sessionid");
        Session session = sessionContainer.get(sessionid);
        String name = request.getParameter("name");
        String description = request.getParameter("description");
        String themeId = request.getParameter("themeId");
        String orgId = request.getParameter("orgId");

        DataSet dataSet = new DataSet();
        dataSet.setOrg(new Org(Integer.valueOf(orgId)));
        dataSet.setName(name);
        dataSet.setDescription(description);
        dataSet.setTheme(new DataTheme(Integer.valueOf(themeId)));
        dataSet.setCreater(new User(session.getUser().getId()));

        dataSet.setCreateTime(new Date());
        com.yeshine.opendata.utils.Result<DataSet> result = dataSetService.create(dataSet);
        if (!result.isSuccess()) {
            throw new AppException("数据集新增失败");
        }
        return new Result(result.getMessage(), dataSet);
    }

    /**
     * 25.数据集修改--- updateDataSet
     *
     * @param id
     * @param name
     * @param description
     * @param themeId
     * @param orgId
     */
    public Result updateDataSet() {

        String sessionid = request.getParameter("sessionid");
        Session session = sessionContainer.get(sessionid);

        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String description = request.getParameter("description");
        String themeId = request.getParameter("themeId");
        String orgId = request.getParameter("orgId");

        DataSet dataSet = dataSetService.getById(Integer.valueOf(id)).getTarget();
        if (dataSet == null) {
            throw new AppException("该数据集不存在");
        }
        dataSet.setName(name);
        dataSet.setDescription(description);
        dataSet.setTheme(new DataTheme(Integer.valueOf(themeId)));
        dataSet.setOrg(new Org(Integer.valueOf(orgId)));

        com.yeshine.opendata.utils.Result<DataSet> result = dataSetService.modify(dataSet);
        if (!result.isSuccess()) {
            throw new AppException("数据集更新失败");
        }
        return new Result(result.getMessage(), dataSet);
    }


    /**
     *26.数据集删除--delDataset
     * @param  sessionid
     * @param  datasetid
     * **/
    public Result delDataset(){
        verifyPermissions();
        String datasetid=request.getParameter("datasetid");
        DataSet dataSet=new DataSet();
        dataSet.setId(Integer.valueOf(datasetid));
        com.yeshine.opendata.utils.Result<DataSet> result=dataSetService.remove(dataSet);
        if (!result.isSuccess()){
            throw  new AppException(result.getMessage());
        }
        return  new Result(result.getMessage(),dataSet);
    }

    public void setDataSetService(IDataSetService dataSetService) {
        this.dataSetService = dataSetService;
    }


    public void setDataService(IDataService dataService) {
        this.dataService = dataService;
    }


    public HttpServletRequest getRequest() {
        return request;
    }

    public void setRequest(HttpServletRequest request) {
        this.request = request;
    }


    public String buildSessionId() {
        return UUID.randomUUID().toString();
    }

    public void verifyPermissions() {
        String sessionid = request.getParameter("sessionid");
        if (!StringUtils.hasLength(sessionid)) {
            throw new AppException("会话ID(session)不能为空");
        }

        Session session = sessionContainer.get(sessionid);
        if (session == null) {
            throw new AppException("未登录，或登录已超时");
        }

    }


}
